package com.hmall.trade.listerner;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.api.item.ItemClient;
import com.hmall.api.pay.PayClient;
import com.hmall.api.trade.po.Order;
import com.hmall.common.constants.Constants;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ljc
 * @version V1.0
 * @date 2025-03-21 15:39
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class PayStatusListerner {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private PayClient payClient;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private ItemClient itemClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.PAY_SUCCESS_QUEUE),
            exchange = @Exchange(value = MqConstants.PAY_EXCHANGE_NAME),
            key = MqConstants.PAY_SUCCESS_KEY
    ))
    public void handlePaySuccess(Long orderId) {
        log.info("收到支付成功消息，订单id:{}", orderId);
        orderService.markOrderPaySuccess(orderId);
    }
    /**
     * 监听支付单状态
     */

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.DELAY_QUEUE),
            exchange = @Exchange(value = MqConstants.DELAY_EXCHANGE_NAME),
            key = MqConstants.DELAY_KEY
    ))
    public void handleDelayPaySuccess(Message message) {
        byte[] body = message.getBody();
        Long orderId = Long.parseLong(new String(body));
        log.info("收到有延迟消息查询订单状态，订单id:{}", orderId);
        if (ObjectUtil.isNull(orderId)){
          return;
        }
        //查询支付状态
        Integer status = payClient.queryPayStatus(orderId);
        if (status.equals(Constants.PAY_STATUS_PAY_SUCCESS)){
            //已支付 ,将订单状态更新为已支付
            orderService.lambdaUpdate()
                    .eq(Order::getId,orderId)
                    .eq(Order::getStatus,Constants.ORDER_STATUS_NO_PAY)
                    .set(Order::getStatus,Constants.ORDER_STATUS_PAY_SUSSESS)
                    .set(Order::getPayTime, LocalDateTime.now())
                    .update();
        }else {
            //未支付，取消订单,修改订单状态为已取消
            orderService.lambdaUpdate()
                    .eq(Order::getId,orderId)
                    .eq(Order::getStatus,Constants.ORDER_STATUS_NO_PAY)
                    .set(Order::getStatus,Constants.ORDER_STATUS_CANCEL)
                    .update();
            //恢复库存
            List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailByOrderId(orderId);
            orderDetails.forEach(orderDetail -> {
                itemClient.recoveryStock(orderDetail.getItemId(),orderDetail.getNum());
            });
        }


    }


}
